package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;

import com.sky.result.PageResult;
import com.sky.service.admin.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * EmployeeServiceImpl类：用来实现EmployeeService接口中定义的功能。
 *
 * @author wangqi
 * @date 2023/12/25 15:24
 */
@Service
@Slf4j
public class EmployeeServiceImp implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        //1.先获取用户名和密码
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //对用户传递过来的密码进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("md5加密后的密文密码：{}", password);

        //2.调用Mapper层提供的数据访问功能获取用户
        Employee employee = employeeMapper.findEmployeeByUsername(username);

        //3.判断用户是否存在，判断密码是否正确，判断用户是否禁用
        if (employee == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if (!employee.getPassword().equals(password)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        return employee;
    }

    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        //1.获取旧密码、新密码、用户id
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
        Long empId = BaseContext.getCurrentId();

        //2.对旧密码、新密码进行加密
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());

        //3.通过旧密码查询用户（校验旧密码是否正确，如果正确才能进行下一步操作）
        Employee employee = employeeMapper.findEmployeeByPasswordAndId(oldPassword, empId);

        //4.判断employee是否存在
        if (employee == null) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //5.如果旧密码正确，则可以将用户的密码修改为新密码
        employeeMapper.updatePassword(empId, newPassword);
    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        //1.由于EmployeeDTO中的属性和Employye的属性只是部分一样，其他的字段可以采用默认值。
        Employee employee = new Employee();
        //2.把EmployeeDto对象的属性值复制到Employee对象中
        BeanUtils.copyProperties(employeeDTO, employee);
        log.info("employee属性值：{}", employee);
        //3.需要对Employee对象中多余的属性单独设置默认值
        //3.1设置默认密码：123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //3.2设置启用状态（启用1、禁用0）
        employee.setStatus(StatusConstant.ENABLE);
        //3.3设置创建时间、修改时间（采用当前系统时间）
        //3.4设置创建人、修改人（当前登录的用户）
        Long empId = BaseContext.getCurrentId();

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empId);
//        employee.setCreateUser(empId);

        //4.调用mapper往数据库中添加元素
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //2.开启分页之后，后面的第一条查询语句会自动加上 limit 分页的标记；
        Page<Employee> employeeList = employeeMapper.pageQuery(employeePageQueryDTO);
        //3.创建响应的返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(employeeList.getTotal());
        pageResult.setRecords(employeeList.getResult());

        return pageResult;
    }

    @Override
    public void update(EmployeeDTO employeeDTO) {
        //1.先创建一个Employee对象
        Employee employee = new Employee();
        //2.把EmployeeDTO对象中的属性复制给Employee对象中
        BeanUtils.copyProperties(employeeDTO,employee);

        //3.设置一些employee必要的属性（id,修改时间、修改人）
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        //4.调用mapper层去修改数据库
        employeeMapper.update(employee);
    }

    @Override
    public Employee findEmployeeById(Long id) {
        Employee employee = employeeMapper.findEmployeeById(id);
        if(employee == null){
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }
        return employee;
    }

    @Override
    public void setStatus(Integer status, Long id) {
        //1.修改employee表中，指定id的status值
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);

        //2.调用mapper修改员工信息
        employeeMapper.update(employee);
    }
}
